package com.example.ktapplication.activity

import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.ktapplication.R
import com.example.ktapplication.adapter.CommomRvAdapter
import com.example.ktapplication.adapter.RvResultAdapter
import com.example.ktapplication.bean.FindArticleDataX
import com.example.ktapplication.bean.HotSearchData
import com.example.ktapplication.model.FindArticleViewModel
import com.example.ktapplication.model.HostSearchViewModel
import com.example.ktapplication.model.SystemViewModel
import com.example.ktapplication.state.FindArticleState
import com.example.ktapplication.state.HostSearchState
import com.example.ktapplication.utils.DpUtils
import com.example.ktapplication.utils.SpacesItemDecoration
import com.example.ktapplication.utils.jumpUrl
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayout
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.google.android.material.textfield.TextInputEditText
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class HostSearchActivity : AppCompatActivity() {

    private lateinit var imgLeft: ImageView
    private lateinit var imgFind: ImageView
    private lateinit var mFlexboxLayout: FlexboxLayout
    private lateinit var txtInput: TextInputEditText

    private lateinit var hostSearchViewModel: HostSearchViewModel
    private lateinit var findViewModel: FindArticleViewModel
    private var stateJob: Job? = null
    private var stateJob2: Job? = null

    private var hostList: MutableList<HotSearchData> = mutableListOf<HotSearchData>()
    private var mArticleList: MutableList<FindArticleDataX> = mutableListOf<FindArticleDataX>()

    private var mRecyclerView: RecyclerView? = null
    private var rvResult: RecyclerView? = null
    private lateinit var adapter: CommomRvAdapter

    lateinit var activity: Activity

    lateinit var llHost: LinearLayout;
    lateinit var llResult: LinearLayout;
    lateinit var txtTitle: TextView;
    private lateinit var mRefresh: SmartRefreshLayout

    var page: Int = 0
    var canFind: Boolean = true
    var isRefresh: Boolean = false
    var isLoadMore: Boolean = false

    private val viewModel by lazy {
        ViewModelProvider(this)[SystemViewModel::class.java]
    }

    private val rvAdapter by lazy {
        RvResultAdapter(this).apply {
            setItemClickListener(object : RvResultAdapter.OnItemClickListener {
                override fun onCollectClick(item: FindArticleDataX) {
                    val id = item.id
                    if (item.collect) {
                        viewModel.unCollect(id) {
                            updateItem(item.apply { collect = false })
                        }
                    } else {
                        viewModel.collect(id) {
                            updateItem(item.apply { collect = true })
                        }
                    }
                }

                override fun onBodyClick(item: FindArticleDataX) {
                    item.let {
                        jumpUrl(it.link, it.title)
                    }
                }
            })
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_host_search)
        hostSearchViewModel = ViewModelProvider(this)[HostSearchViewModel::class.java]
        findViewModel = ViewModelProvider(this)[FindArticleViewModel::class.java]
        activity = this
        initView()
        initData()
        waitData()
    }

    fun initView() {
        mRefresh = findViewById(R.id.smartRefreshLayout)
        txtTitle = findViewById(R.id.txt_title)
        llHost = findViewById<LinearLayout>(R.id.ll_host_search)
        llResult = findViewById<LinearLayout>(R.id.ll_host_result)
        imgFind = findViewById<ImageView>(R.id.img_find)
        imgFind.setOnClickListener(View.OnClickListener {
            if (canFind) {
                mArticleList.clear()
                findArticle()
                page++
            } else {
                llHost.visibility = View.VISIBLE
                txtInput.visibility = View.VISIBLE
                llResult.visibility = View.GONE
                txtTitle.visibility = View.GONE
                canFind = true
                mArticleList.clear()
                Glide.with(activity)
                    .load(R.mipmap.icon_find)
                    .into(imgFind)
            }
        })
        imgLeft = findViewById<ImageView>(R.id.img_menu)
        imgLeft.setOnClickListener(View.OnClickListener {
            finish()
        })
        txtInput = findViewById<TextInputEditText>(R.id.txtInput)
        mRecyclerView = findViewById(R.id.recyclerView)
        val flexboxLayoutManager = FlexboxLayoutManager(activity)
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP)
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
        mRecyclerView!!.layoutManager = flexboxLayoutManager
        adapter = CommomRvAdapter(activity, hostList, R.layout.host_rv_itme)
        mRecyclerView!!.adapter = adapter
        mRecyclerView!!.addItemDecoration(
            SpacesItemDecoration(DpUtils.getInstance().px2dp(activity, 30F))
        );
        adapter.notifyDataSetChanged()
        adapter.setOnItemClickListener(CommomRvAdapter.OnItemClickListener { position ->
            txtInput.setText(hostList[position].name)
        })

        rvResult = findViewById(R.id.rvResult)
        rvResult!!.layoutManager = LinearLayoutManager(this.activity)
        rvAdapter.setData(mArticleList)
        rvResult!!.adapter = rvAdapter
        rvAdapter.notifyDataSetChanged()
        //上拉加载
        mRefresh.setOnLoadMoreListener(object : OnLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                isRefresh = false
                findArticle()
                page++
                refreshLayout.finishLoadMore()
            }
        })
        //下拉刷新
        mRefresh.setOnRefreshListener(object : OnRefreshListener {

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 0
                isRefresh = true
                isLoadMore = false
                findArticle()
                refreshLayout.finishRefresh()
            }
        })
    }

    fun waitData() {
        stateJob = lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            hostSearchViewModel.state.collect { state ->
                when (state) {
                    is HostSearchState.OnSuccess -> {
                        if (state.host != null) {
                            if (state.host!!.errorCode == 0) {
                                withContext(Dispatchers.Main) {
                                    ///Main线程
                                    hostList.addAll(state.host!!.data)
                                    adapter.setData(state.host!!.data)
                                }
                            } else {

                            }
                            state.host!!.count += 1
                        }

                    }

                    is HostSearchState.OnError -> {
                        val error = state.exception!!.message;
                    }
                }
            }
        }
        stateJob2 = lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            findViewModel.state.collect { state ->
                when (state) {
                    is FindArticleState.OnSuccess -> {
                        if (state.article != null) {
                            if (state.article!!.errorCode == 0) {
                                withContext(Dispatchers.Main) {
                                    ///Main线程
                                    canFind = false
                                    llHost.visibility = View.GONE
                                    llResult.visibility = View.VISIBLE
                                    txtTitle.visibility = View.VISIBLE
                                    txtInput.visibility = View.GONE
                                    Glide.with(activity)
                                        .load(R.mipmap.close)
                                        .into(imgFind)
                                    if (isLoadMore) {
                                        mArticleList.addAll(state.article!!.data.datas)
                                    } else if (isRefresh) {
                                        mArticleList.clear()
                                        mArticleList.addAll(state.article!!.data.datas)
                                    } else {
                                        mArticleList.clear()
                                        mArticleList.addAll(state.article!!.data.datas)
                                    }
                                    rvAdapter.setData(mArticleList)
                                }
                            } else {

                            }
                            state.article!!.count += 1
                        }

                    }

                    is FindArticleState.OnError -> {
                        val error = state.exception!!.message;
                    }
                }
            }
        }
    }

    fun initData() {
        hostSearchViewModel.host()
    }

    fun findArticle() {
        findViewModel.findAritcleData(page, txtInput.text.toString())
    }

    override fun onDestroy() {
        super.onDestroy()
        stateJob!!.cancel()
        stateJob2!!.cancel()
    }
}